package com.ljfiction.book.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ljfiction.book.Dialog.ImageDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.Dialog.PhoneBangding;
import com.ljfiction.book.MyView.CircularImageView;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.Md5;
import com.ljfiction.book.http.UserBean;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.PreferencesTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.model.HttpHeaders;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.Response;

public class MymessageActivity extends BaseActivity {

    @BindView(R.id.toset1)
    ImageView toset1;
    @BindView(R.id.myimage)
    CircularImageView myimage;
    @BindView(R.id.setmyimage)
    RelativeLayout setmyimage;
    @BindView(R.id.toset2)
    ImageView toset2;
    @BindView(R.id.username_mymessage)
    TextView usernameMymessage;
    @BindView(R.id.setnickname)
    RelativeLayout setnickname;
    @BindView(R.id.textView)
    TextView textView;

    @BindView(R.id.usersex)
    TextView usersex;
    @BindView(R.id.setsex)
    RelativeLayout setsex;
    @BindView(R.id.toset4)
    ImageView toset4;
    @BindView(R.id.signature)
    TextView signature;
    @BindView(R.id.qianming)
    RelativeLayout qianming;
    @BindView(R.id.toset6)
    ImageView toset6;
    @BindView(R.id.unboundmailbox)
    TextView unboundmailbox;
    @BindView(R.id.bangdingyouxiang)
    RelativeLayout bangdingyouxiang;
    @BindView(R.id.toset7)
    ImageView toset7;
    @BindView(R.id.modifypassword)
    RelativeLayout modifypassword;

    @BindView(R.id.zhanghao)
    TextView zhanghao;
    @BindView(R.id.messageback)
    ImageView messageback;
    @BindView(R.id.shoujihaolayout)
    RelativeLayout shoujihaolayout;
    private ImageDialog imageDialog;
    private Intent intent;
    private NoBackgLodDialog noBackgLodDialog;
private PhoneBangding phoneBangdingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mymessage);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        Glide.with(this).load(UserManageBean.userBean.getUserHeadPortraitURL()).into(myimage);
        usernameMymessage.setText(UserManageBean.userBean.getPseudonym());
        usersex.setText(UserManageBean.userBean.getUserSex());
        signature.setText(UserManageBean.userBean.getUserAutograph());
        if (UserManageBean.userBean.getUserPhone().equals("0")) {
            zhanghao.setText("未绑定");
        } else {
            zhanghao.setText(UserManageBean.userBean.getUserPhone());
        }

        unboundmailbox.setText(UserManageBean.userBean.getUserEmail());
        /* mypone.setText(UserManageBean.userBean.getUserName().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));*/
    }

    @OnClick({R.id.setmyimage, R.id.setnickname, R.id.setsex, R.id.qianming, R.id.bangdingyouxiang, R.id.modifypassword, R.id.messageback, R.id.shoujihaolayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.messageback:
                goBack();
                break;
            case R.id.setmyimage:
                imageDialog = new ImageDialog(MymessageActivity.this, "logoName.jpg", new ImageDialog.Listener() {
                    @Override
                    public void getImage(final Bitmap photo) {
                        OkHttpUtils.post(HttpManager.IP + "/sys-UserAvatarimgUpload")

                                .params("file", new File(getExternalCacheDir() + "/logoName.jpg"))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onBefore(BaseRequest request) {
                                        super.onBefore(request);
                                        if (noBackgLodDialog == null) {
                                            noBackgLodDialog = new NoBackgLodDialog(MymessageActivity.this, true);
                                        }
                                        noBackgLodDialog.show();
                                    }

                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        if (noBackgLodDialog != null) {
                                            noBackgLodDialog.dismis();
                                        }
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                myimage.setImageBitmap(photo);
                                                UserManageBean.backgroundRiches(MymessageActivity.this);
                                                showToast(jsonObject.getString("msg"));
                                            } else {
                                                if (jsonObject.getInt("returnCode") == 400) {
                                                    Intent intent = new Intent(MymessageActivity.this, LoginActivity.class);
                                                    startActivity(intent);
                                                }
                                                showToast(jsonObject.getString("msg"));
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    }
                });

                break;
            case R.id.setnickname:
                break;
            case R.id.setsex:
                break;
            case R.id.qianming:
                intent = new Intent(MymessageActivity.this, UpdataEmailActivity.class);
                startActivity(intent);
                break;
            case R.id.bangdingyouxiang:
                intent = new Intent(MymessageActivity.this, TomessageActivity.class);
                startActivity(intent);
                break;
            case R.id.modifypassword:
                intent = new Intent(MymessageActivity.this, UpdataPassWordActivity.class);
                startActivity(intent);
                break;
            case R.id.shoujihaolayout:
                if (!UserManageBean.isLogin(MymessageActivity.this)){
                    return;
                }
                if (UserManageBean.userBean.getUserPhone().equals("0")){
                    if (phoneBangdingDialog == null) {
                        phoneBangdingDialog = new PhoneBangding(MymessageActivity.this);
                        phoneBangdingDialog.setListener(new PhoneBangding.Listener() {
                            @Override
                            public void giveyanzhengnoLogin() {
                                Intent intent=new Intent(MymessageActivity.this,LoginActivity.class);
                                startActivity(intent);
                                return;

                            }

                            @Override
                            public void setok() {
                                UserManageBean.backgroundRiches(MymessageActivity.this);
                                zhanghao.setText(UserManageBean.userBean.getUserPhone());
                            }

                            @Override
                            public void clickquhao() {
                                Intent   intent=new Intent(MymessageActivity.this,SelectquhaoActivity.class);
                                startActivityForResult(intent,10);
                            }
                        });
                    }
                    phoneBangdingDialog.show();
                }else {
                    intent = new Intent(MymessageActivity.this, ChangePhoneActivity.class);
                    startActivityForResult(intent,10);
                }

                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK ) {
            imageDialog.onActivityResult(data, requestCode, 1);
        }else if (resultCode==10&&requestCode==10){
                zhanghao.setText(UserManageBean.userBean.getUserPhone());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initView();
        // toupdatauser();

    }

    private void toupdatauser() {
        OkHttpUtils.post(HttpManager.IP + "/person-login")
                .params("userName", PreferencesTool.getUserName(this).toString())
                .params("userPassword", Md5.encryption(PreferencesTool.getPassWord(this).toString()))
                .params("terminal", "2")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        // 取得sessionid.
                        try {
                          /*  Headers headers = response.headers();
                            List<String> cookies = headers.values("Set-Cookie");
                            String session = cookies.get(0);
                            session = session.substring(0, session.indexOf(";"));
                            SettingManager.getInstance().savesessionId(session);*/
                            Gson gson = new Gson();
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                if (user.getsTR() == 1) {
                                    Tool.xmjaddtishi(MymessageActivity.this);


                                    UserManageBean.userBean.setsTR(0);
                                }
                                UserManageBean.userBean = user;
                                SettingManager.getInstance().savesessionId(user.getToken());
                                UserManageBean.setIsLogin(true);
                                initView();
                            } else {
                                UserManageBean.setIsLogin(false);
                            }

                        } catch (Exception e) {
                            UserManageBean.setIsLogin(false);
                            e.printStackTrace();
                        }

                    }
                });
    }
}
